package com.kwan.widget.tool.recycle

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

class GridItemDecorationSpanSizeLookup : RecyclerView.ItemDecoration {
    protected var mSpace = 10
    private var mIncludeEdge = true

    constructor(space: Int) {
        mSpace = space
    }

    constructor(space: Int, includeEdge: Boolean) {
        mSpace = space
        mIncludeEdge = includeEdge
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val gridLayoutManager = parent.layoutManager as GridLayoutManager?

        val position = parent.getChildLayoutPosition(view)

        //列数
        var spanCount = gridLayoutManager!!.spanSizeLookup.getSpanSize(position)
        val column = position % spanCount



        if (mIncludeEdge) {
            outRect.left = mSpace - column * mSpace / spanCount
            outRect.right = (column + 1) * mSpace / spanCount

            if (position < spanCount) {
                outRect.top = mSpace
            }

            outRect.bottom = mSpace
        } else {

            outRect.left = column * mSpace / spanCount
            //outRect.right = mSpace - (column + 1) * mSpace / spanCount

            outRect.right = mSpace - (column) * mSpace / spanCount

            if (position >= spanCount) {
                outRect.top = mSpace
            }
        }


    }
}